﻿using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data;
using eDoc.DAL;
using System.Configuration;
using System.Common;
using System.Web.Services.Protocols;
using eDocWS.Common;
using eDocWS.Objects;
using System.Web;

namespace eDocWS
{
    /// <summary>
    /// Summary description for service
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class service : System.Web.Services.WebService
    {
        private string DomainInstall = ConfigurationManager.AppSettings["DomainInstall"].ToString();
        private readonly PrivateFuncs func = new PrivateFuncs();

        [WebMethod(Description = "Thong tin dang nhap: 0: thanh cong;  1: sai user hoac sai mat khau; 2: sai uidi; 3: uuid bi blacklist; 4: co loi xay ra")]

        public string LoginApp(string username, string password, string udid, string partner)
        {
            string result = "1";
            try
            {
                if (!func.CheckBlacklist(udid))
                {
                    return "3";
                }

                string strpassmd5 = Encryptor.GetMd5Hash(password).ToUpper();
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Login_App(username, strpassmd5, udid, partner);
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    result = dt.Rows[0][0].ToString();
                }
            }
            catch (Exception ex)
            {
                result = "4";
                Global.log.Error(ex);
                throw;
            }
            return result;
        }

        [WebMethod(Description = "Tra ve thong tin FTP cua nguoi dung theo Udid")]
        public FTPResponse retrieveFTPServer(string udid, string partner)
        {
            FTPResponse ftpRes = new FTPResponse();
            try
            {

                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_FTP_by_Udid(udid, partner);
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    string UserFTP = dt.Rows[0]["UserFTP"].ToString();
                    string PassFTP = dt.Rows[0]["PassFTP"].ToString();
                    string HostFTP = dt.Rows[0]["HostFTP"].ToString();
                    string PortFTP = dt.Rows[0]["PortFTP"].ToString();
                    string Passive = dt.Rows[0]["Passive"].ToString();
                    if (Passive == "True")
                        Passive = "yes";
                    else
                        Passive = "no";

                    ftpRes.ftpHost = HostFTP;
                    ftpRes.ftpPassword = PassFTP;
                    ftpRes.ftpPassive = Passive;
                    ftpRes.ftpPort = PortFTP;
                    ftpRes.ftpUsername = UserFTP;


                }
            }
            catch (Exception ex)
            {
                Global.log.Error(ex);
                throw;
            }

            return ftpRes;
        }


        [WebMethod(Description = "Tra ve danh sach FTP cua nguoi dung theo PartnerCode")]
        public List<FTPResponse> retrieveFTPServers(string partner)
        {
            List<FTPResponse> ftp = new List<FTPResponse>();

            try
            {
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_FTP_by_PartnerCode(partner);
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        FTPResponse ftpRes = new FTPResponse();

                        string UserFTP = dt.Rows[i]["UserFTP"].ToString();
                        string PassFTP = dt.Rows[i]["PassFTP"].ToString();
                        string HostFTP = dt.Rows[i]["HostFTP"].ToString();
                        string PortFTP = dt.Rows[i]["PortFTP"].ToString();
                        string Passive = dt.Rows[i]["Passive"].ToString();
                        string Name = dt.Rows[i]["Name"].ToString();
                        if (Passive == "True")
                            Passive = "yes";
                        else
                            Passive = "no";


                        ftpRes.ftpHost = HostFTP;
                        ftpRes.ftpPassword = PassFTP;
                        ftpRes.ftpPassive = Passive;
                        ftpRes.ftpPort = PortFTP;
                        ftpRes.ftpUsername = UserFTP;
                        ftpRes.ftpName = Name;

                        ftp.Add(ftpRes);
                    }

                }
            }
            catch (Exception ex)
            {
                Global.log.Error(ex);
                throw;
            }

            return ftp;
        }

        [WebMethod(Description = "Tra ve danh sach FTP cua nguoi dung theo PartnerCode va loai Server FTP. Neu Type=0: server FTP DOC; Type = 1 : server FTP Verify")]
        public List<FTPResponse> FTPServers(string partner, int Type)
        {
            List<FTPResponse> ftp = new List<FTPResponse>();
            try
            {
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_FTP_by_PartnerCode_Type(partner, Type);
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        FTPResponse ftpRes = new FTPResponse();

                        string UserFTP = dt.Rows[i]["UserFTP"].ToString();
                        string PassFTP = dt.Rows[i]["PassFTP"].ToString();
                        string HostFTP = dt.Rows[i]["HostFTP"].ToString();
                        string PortFTP = dt.Rows[i]["PortFTP"].ToString();
                        string Passive = dt.Rows[i]["Passive"].ToString();
                        string Name = dt.Rows[i]["Name"].ToString();
                        string TSL = dt.Rows[i]["TSL"].ToString();
                        if (Passive == "True")
                            Passive = "yes";
                        else
                            Passive = "no";


                        ftpRes.ftpHost = HostFTP;
                        ftpRes.ftpPassword = PassFTP;
                        ftpRes.ftpPassive = Passive;
                        ftpRes.ftpPort = PortFTP;
                        ftpRes.ftpUsername = UserFTP;
                        ftpRes.ftpName = Name;
                        ftpRes.ftpTSL = TSL;
                        ftp.Add(ftpRes);
                    }

                }
            }
            catch (Exception ex)
            {
                Global.log.Error(ex);
                throw;
            }
            return ftp;
        }

        [WebMethod(Description = "Tra ve danh sach FTP Verify theo PartnerCode")]
        public List<FTPResponse> retrieveFTPServersVerify(string partner)
        {
            List<FTPResponse> ftp = new List<FTPResponse>();
            try
            {
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_FTP_by_PartnerCode_Type(partner, 1);
                    db.Close();
                    db.Dispose();
                }
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        FTPResponse ftpRes = new FTPResponse();

                        string UserFTP = dt.Rows[i]["UserFTP"].ToString();
                        string PassFTP = dt.Rows[i]["PassFTP"].ToString();
                        string HostFTP = dt.Rows[i]["HostFTP"].ToString();
                        string PortFTP = dt.Rows[i]["PortFTP"].ToString();
                        string Passive = dt.Rows[i]["Passive"].ToString();
                        string Name = dt.Rows[i]["Name"].ToString();
                        if (Passive == "True")
                            Passive = "yes";
                        else
                            Passive = "no";


                        ftpRes.ftpHost = HostFTP;
                        ftpRes.ftpPassword = PassFTP;
                        ftpRes.ftpPassive = Passive;
                        ftpRes.ftpPort = PortFTP;
                        ftpRes.ftpUsername = UserFTP;
                        ftpRes.ftpName = Name;

                        ftp.Add(ftpRes);
                    }

                }
            }
            catch (Exception ex)
            {
                Global.log.Error(ex);
                throw;
            }

            return ftp;
        }

        [WebMethod(Description = "Tra ve Ung dung voi Version moi nhat theo APP_ID")]
        public AppVersionInfo NewVersion(string AppID, string CurrentVersion, string BinaryBuildTime)
        {
            AppVersionInfo result = new AppVersionInfo();
            try
            {

                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_AppPlist_by_AppID(AppID); 
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    DateTime buildTime = new DateTime();
                    string newVersion = dt.Rows[0]["AppVersion"].ToString().Trim();
                    int compare = func.CompareVersion(CurrentVersion, newVersion);
                    //buildTime = Convert.ToDateTime(dt.Rows[0]["AppPListDateCreated"]);
                    if (compare > 0)
                    {
                        result.Version = dt.Rows[0]["AppVersion"].ToString();
                        if (dt.Rows[0]["AppPublishedDate"] != null && dt.Rows[0]["AppPublishedDate"].ToString() != "")
                        {
                            result.DatePublished = Convert.ToDateTime(dt.Rows[0]["AppPublishedDate"]).ToString("ddMMMyy");
                        }
                        else
                        {
                            result.DatePublished = "";
                        }

                        string filePlist = dt.Rows[0]["AppPlistPath"].ToString().Replace("fileinfo", "fileplist");
                        string appKey = dt.Rows[0]["AppKey"].ToString();
                        string urlDownload = DomainInstall.TrimEnd('/') + "/plist.aspx?ak=" + appKey;
                        result.InstallLink = urlDownload;

                        return result;
                    }

                    result.Version = CurrentVersion;
                    result.DatePublished = Convert.ToDateTime(BinaryBuildTime).ToString("ddMMMyy");
                    result.InstallLink = "";

                }


            }
            catch (Exception soapEx)
            {
                Global.log.Error(soapEx);
            }

            return result;
        }

        [WebMethod(Description = "Log lai thong tin Sync du lieu")]
        public Message LogSync(string Uuid, string Email, string Content, int ErrorCode)
        {
            Message message = new Message();
            try
            {
                if (!func.CheckBlacklist(Uuid))
                {
                    message.Title = "Uuid: " + Uuid + " in blacklist.";
                    message.Content = "Uuid: " + Uuid + " in blacklist.";
                    message.Result = false;

                    return message;
                }

                using (MainDB db = new MainDB())
                {
                    db.StoredProcedures.VNA_Insert_LogSync(Uuid, Email, Content, ErrorCode, "", "", "", "", "", "", "", 0);
                    db.Dispose();
                }

                message.Title = "Sync data success";
                message.Content = "Sync data success at: " + DateTime.Now;
                message.Result = true;
            }
            catch (Exception ex)
            {

                message.Title = "Sync data false";
                message.Content = "Sync data false at: " + DateTime.Now + ". " + ex.Message;
                message.Result = false;
                Global.log.Error(ex);
                throw;
            }

            return message;
        }

        [WebMethod(Description = "Log lai thong tin SyncDetail")]
        public Message LogSyncDetail(string Uuid, string Email, string Content, int ErrorCode, string DocumentAttributes, string AppID, string IpadName, string BuildMode, string Msisdn, string Carrier, string Manufacture, int FilesCount)
        {
            Message message = new Message();
            try
            {
                if (!func.CheckBlacklist(Uuid))
                {
                    message.Title = "Uuid: " + Uuid + " in blacklist.";
                    message.Content = "Uuid: " + Uuid + " in blacklist.";
                    message.Result = false;

                    return message;
                }

                using (MainDB db = new MainDB())
                {
                    db.StoredProcedures.VNA_Insert_LogSync(Uuid, Email, Content, ErrorCode, DocumentAttributes, AppID, IpadName, BuildMode, Msisdn, Carrier, Manufacture, FilesCount);
                    db.Dispose();
                }

                message.Title = "Sync data success";
                message.Content = "Sync data success at: " + DateTime.Now;
                message.Result = true;
            }
            catch (Exception ex)
            {

                message.Title = "Sync data false";
                message.Content = "Sync data false at: " + DateTime.Now + ". " + ex.Message;
                message.Result = false;
                Global.log.Error(ex);
                throw;
            }

            return message;
        }

        [WebMethod(Description = "Kích thoạt thiết bị người dùng")]
        public Message DevicesActive(string Uuid, string Email, string Password, string AppID, string Push_ID)
        {
            Message message = new Message();
            try
            {
                if (!func.CheckBlacklist(Uuid))
                {
                    message.Title = "Uuid: " + Uuid + " in blacklist.";
                    message.Content = "Uuid: " + Uuid + " in blacklist.";
                    message.Result = false;

                    return message;
                }

                if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(AppID))
                {
                    message.Title = "Email or AppID is null";
                    message.Content = "Email or AppID is null";
                    message.Result = false;

                    return message;
                }

                DataTable dt = new DataTable();
                DataTable dtInsert = new DataTable();

                string checkUser = "SUCCESS";
                string strEmail = "";

                RequestAuthen requestAuthen = new RequestAuthen
                {
                    username = Email,
                    password = HttpUtility.UrlEncode(Password)
                };

                ResponseAuthen responseAuthe = func.GetAuthen(requestAuthen);

                checkUser = responseAuthe.Status;
                
                if (checkUser == "SUCCESS")
                {
                    using (MainDB db = new MainDB())
                    {
                        // Kiem tra xem co phai la email super hay ko ?
                        if (func.CheckEmailSupper(Email))
                        {
                            message = func.InsertDevice(db, Uuid, Email, Password, AppID, Push_ID,"");                            
                        }
                        else
                        {
                            dt = db.StoredProcedures.VNA_Select_Devices_by_Email(Email.Trim());

                            if (dt != null && dt.Rows.Count > 0)
                            {
                                if (CheckUuid(Uuid, dt))
                                {
                                    message.Title = "This device is already activated";
                                    message.Content = "This device is already activated: " + Uuid +
                                                      " with email: " +
                                                      Email + " success!";
                                    message.Result = true;
                                }
                                else
                                {
                                    if (dt.Rows.Count >= 2)
                                    {
                                        message.Title = "Two devices have been actived";
                                        message.Content = "Two devices have been actived with Email: " + Email + " ";
                                        message.Result = false;
                                    }
                                    else
                                    {
                                        message = func.InsertDevice(db, Uuid, Email, Password, AppID, Push_ID, "");
                                    }
                                }
                            }
                            else
                            {
                                message = func.InsertDevice(db, Uuid, Email, Password, AppID, Push_ID, "");
                            }
                        }

                        db.Close();
                        db.Dispose();

                        message.FullName = string.IsNullOrEmpty(responseAuthe.FullName) ? responseAuthe.UserName : responseAuthe.FullName;
                        message.UserName = responseAuthe.UserName;
                        message.Code = responseAuthe.Code;
                        message.Email = string.IsNullOrEmpty(responseAuthe.Email) ? "AITS" : responseAuthe.Email;
                        message.TitleAuthe = responseAuthe.Title;
                    }
                }
                else
                {
                    message.Title = "Login false";
                    message.Content = "Login with email: " + Email + " false. Message Error: " + responseAuthe.MessageError;
                    message.Result = false;

                }
            }
            catch (Exception ex)
            {
                message.Title = ex.Message;
                message.Content = ex.Message;
                message.Result = false;

                Global.log.Error(ex);
            }
            return message;
        }

        [WebMethod(Description = "Kích thoạt thiết bị người dùng")]
        public Message DevicesActiveDetail(string Uuid, string Email, string Password, string AppID, string Push_ID, string IpadName)
        {
            Message message = new Message();
            try
            {
                if (!func.CheckBlacklist(Uuid))
                {
                    message.Title = "Uuid: " + Uuid + " in blacklist.";
                    message.Content = "Uuid: " + Uuid + " in blacklist.";
                    message.Result = false;

                    return message;
                }

                if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(AppID))
                {
                    message.Title = "Email or AppID is null";
                    message.Content = "Email or AppID is null";
                    message.Result = false;

                    return message;
                }

                DataTable dt = new DataTable();
                DataTable dtInsert = new DataTable();

                string checkUser = "SUCCESS";
                string strEmail = "";

                RequestAuthen requestAuthen = new RequestAuthen
                {
                    username = Email,
                    password = HttpUtility.UrlEncode(Password)
                };

                ResponseAuthen responseAuthe = func.GetAuthen(requestAuthen);

                checkUser = responseAuthe.Status;

                if (checkUser == "SUCCESS")
                {
                    using (MainDB db = new MainDB())
                    {
                        // Kiem tra xem co phai la email super hay ko ?
                        if (func.CheckEmailSupper(Email))
                        {
                            message = func.InsertDevice(db, Uuid, Email, Password, AppID, Push_ID, IpadName);
                        }
                        else
                        {
                            dt = db.StoredProcedures.VNA_Select_Devices_by_Email(Email.Trim());

                            if (dt != null && dt.Rows.Count > 0)
                            {
                                if (CheckUuid(Uuid, dt))
                                {
                                    message.Title = "This device is already activated";
                                    message.Content = "This device is already activated: " + Uuid +
                                                      " with email: " +
                                                      Email + " success!";
                                    message.Result = true;
                                }
                                else
                                {
                                    if (dt.Rows.Count >= 2)
                                    {
                                        message.Title = "Two devices have been actived";
                                        message.Content = "Two devices have been actived with Email: " + Email + " ";
                                        message.Result = false;
                                    }
                                    else
                                    {
                                        message = func.InsertDevice(db, Uuid, Email, Password, AppID, Push_ID, IpadName);
                                    }
                                }
                            }
                            else
                            {
                                message = func.InsertDevice(db, Uuid, Email, Password, AppID, Push_ID, IpadName);
                            }
                        }

                        db.Close();
                        db.Dispose();

                        message.FullName = string.IsNullOrEmpty(responseAuthe.FullName) ? responseAuthe.UserName : responseAuthe.FullName;
                        message.UserName = responseAuthe.UserName;
                        message.Code = responseAuthe.Code;
                        message.Email = string.IsNullOrEmpty(responseAuthe.Email) ? "AITS" : responseAuthe.Email;
                        message.TitleAuthe = responseAuthe.Title;
                    }
                }
                else
                {
                    message.Title = "Login false";
                    message.Content = "Login with email: " + Email + " false. Message Error: " + responseAuthe.MessageError;
                    message.Result = false;

                }
            }
            catch (Exception ex)
            {
                message.Title = ex.Message;
                message.Content = ex.Message;
                message.Result = false;

                Global.log.Error(ex);
            }
            return message;
        }
         
        /// <summary>
        /// Kiem tra uuid da co trong db chua
        /// </summary>
        /// <param name="uuid"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private bool CheckUuid(string uuid, DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["uuid"].Equals(uuid))
                {
                    return true;
                }
            }
            return false;
        }

        [WebMethod(Description = "Kiểm tra xem thiết bị được kích hoạt hay chưa theo Uuid")]
        public Message CheckDeviceActive(string Uuid)
        {
            Message message = new Message();
            try
            {
                if (!func.CheckBlacklist(Uuid))
                {
                    message.Title = "Uuid: " + Uuid + " has in blacklist.";
                    message.Content = "Uuid: " + Uuid + " has in blacklist.";
                    message.Result = false;
                    message.Email = "";
                    return message;
                }

                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_Devices_by_Uuid(Uuid);
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    if (Convert.ToBoolean(dt.Rows[0]["Active"]))
                    {
                        message.Title = "Device has Actived";
                        message.Content = "Device has Actived";
                        message.Result = true;
                        message.Email = dt.Rows[0]["Email"].ToString();
                    }
                    else
                    {
                        message.Title = "Device has not Actived";
                        message.Content = "Device has not Actived";
                        message.Result = false;
                        message.Email = dt.Rows[0]["Email"].ToString();
                    }
                }
                else
                {
                    message.Title = "Device not found";
                    message.Content = "Device not found";
                    message.Result = false;
                    message.Email = "";
                }
            }
            catch (Exception ex)
            {
                message.Title = ex.Message;
                message.Content = ex.Message;
                message.Result = false;
                message.Email = "";
                Global.log.Error(ex);
            }

            return message;
        }

        [WebMethod(Description = "Huy kich hoat cua thiet bi theo email (user) nguoi dung")]
        public Message DeActive(string Email)
        {
            Message message = new Message();
            try
            {
                using (MainDB db = new MainDB())
                {
                    db.StoredProcedures.VNA_Devices_DeActive(Email);
                    db.Dispose();
                }

                message.Title = "Deactive success with email(user) : " + Email;
                message.Content = "Deactive success at: " + DateTime.Now + " with email(user): " + Email;
                message.Result = true;
            }
            catch (Exception ex)
            {
                message.Title = "Deactive false";
                message.Content = "Deactive false: " + DateTime.Now + ". " + ex.Message;
                message.Result = false;
                Global.log.Error(ex);
            }


            return message;
        }

        [WebMethod(Description = "Log Download")]
        public Message LogDownload(string Username, string AppID, string Email, string Uuid, string BinaryBuildTime, string ExpirationDate, string IpadName, string DeviceToken)
        {
            Message message = new Message();
            try
            {
                using (MainDB db = new MainDB())
                {
                    db.StoredProcedures.VNA_Insert_LogDownload(Username, AppID, Email, Uuid, BinaryBuildTime, Convert.ToDateTime(ExpirationDate), IpadName, DeviceToken);
                    db.Dispose();
                }

                message.Title = "LogDownload: " + Uuid + " - " + AppID + " - " + Username + " - " + Email + " - " + IpadName + " - " + ExpirationDate + " - " + DeviceToken;
                message.Content = "LogDownload: " + Uuid + " - " + AppID + " - " + Username + " - " + Email + " - " + IpadName + " - " + ExpirationDate + " - " + DeviceToken;
                message.Result = true;
            }
            catch (Exception ex)
            {
                message.Title = "Deactive false";
                message.Content = "Deactive false: " + DateTime.Now + ". " + ex.Message;
                message.Result = false;
                Global.log.Error(ex);
                throw;
            }


            return message;
        }

        [WebMethod(Description = "Check Blacklist theo Uuid")]
        public Message BlacklistCheck(string uuid)
        {
            Message message = new Message();
            try
            {
                DataTable dtBlacklist = new DataTable();
                using (MainDB db = new MainDB())

                    if (!func.CheckBlacklist(uuid))
                    {
                        message.Title = "Uuid: " + uuid + " has in blacklist.";
                        message.Content = "Uuid: " + uuid + " has in blacklist.";
                        message.Result = false;
                    }
                    else
                    {
                        message.Title = "Uuid: " + uuid + " is ok.";
                        message.Content = "Uuid: " + uuid + " is ok.";
                        message.Result = true;
                    }

            }
            catch (Exception ex)
            {
                message.Title = ex.Message;
                message.Content = ex.Message;
                message.Result = false;
                Global.log.Error(ex);
                throw;
            }
            return message;
        }

        [WebMethod(Description = "Them moi Uuid vao Blacklist theo AppID")]
        public Message Blacklist_Insert(string uuid, string appId)
        {
            Message mess = new Message();
            try
            {
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Insert_Blacklist(uuid, appId, "");
                    db.Close();
                    db.Dispose();
                }

                int result = 0;

                if (dt != null)
                {
                    result = Convert.ToInt32(dt.Rows[0][0]);

                    if (result == 0)
                    {
                        mess.Result = true;
                        mess.Title = "Insert success!";
                        mess.Content = "Insert success!";
                    }
                    else
                    {
                        mess.Result = false;
                        mess.Title = "Uuid: " + uuid + " and AppID: " + appId + " has in Blacklist.";
                        mess.Content = "Uuid: " + uuid + " and AppID: " + appId + " has in Blacklist.";
                    }
                }
                else
                {
                    mess.Result = false;
                    mess.Title = "Insert false";
                    mess.Content = "Insert false";
                }
            }
            catch (Exception ex)
            {
                mess.Title = ex.Message;
                mess.Content = ex.Message;
                mess.Result = false;
                Global.log.Error(ex);
                throw;
            }


            return mess;

        }

        [WebMethod(Description = "Xoa blacklist theo Uuid")]
        public Message Blacklist_Delete(string uuid)
        {
            Message mess = new Message();
            try
            {
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Delete_Blacklist_by_Uuid(uuid);
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows[0][0].ToString() == "0")
                    {
                        mess.Result = false;
                        mess.Title = "Uuid:" + uuid + " hasn't in Blacklist";
                        mess.Content = "Uuid:" + uuid + " hasn't in Blacklist";
                    }
                    else
                    {
                        mess.Result = true;
                        mess.Title = "Delete Uuid:" + uuid + " success";
                        mess.Content = "Delete Uuid:" + uuid + " success";
                    }
                }
                else
                {
                    mess.Result = false;
                    mess.Title = "Delete False.";
                    mess.Content = "Delete False.";
                }
            }
            catch (Exception ex)
            {
                mess.Title = ex.Message;
                mess.Content = ex.Message;
                mess.Result = false;
                Global.log.Error(ex);
                throw;
            }
            return mess;
        }

        [WebMethod(Description = "Xoa blacklist theo Uuid va AppID")]
        public Message Blacklist_Delete_with_Uuid_AppId(string uuid, string appID)
        {
            Message mess = new Message();
            try
            {
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Delete_Blacklist_by_Uuid_and_AppID(uuid, appID);
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows[0][0].ToString() == "0")
                    {
                        mess.Result = false;
                        mess.Title = "Uuid:" + uuid + " and AppID: " + appID + " hasn't in Blacklist";
                        mess.Content = "Uuid:" + uuid + " and AppID: " + appID + " hasn't in Blacklist";
                    }
                    else
                    {
                        mess.Result = true;
                        mess.Title = "Delete Uuid:" + uuid + " and AppID: " + appID + " success";
                        mess.Content = "Delete Uuid:" + uuid + " and AppID: " + appID + " success";
                    }
                }
                else
                {
                    mess.Result = false;
                    mess.Title = "Delete False.";
                    mess.Content = "Delete False.";
                }
            }
            catch (Exception ex)
            {
                mess.Title = ex.Message;
                mess.Content = ex.Message;
                mess.Result = false;
                Global.log.Error(ex);
                throw;
            }
            return mess;
        }

        [WebMethod(Description = "Lay thong tin thiet bi, email da kich hoat va chua kich hoat")]
        public List<Devices> GetDevices()
        {
            List<Devices> listDevice = new List<Devices>();
            try
            {
                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_Devices_All();
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        Devices deviceItem = new Devices();
                        if (dr["Active"] != null && !string.IsNullOrEmpty(dr["Active"].ToString()))
                            deviceItem.Actived = Convert.ToBoolean(dr["Active"].ToString());
                        deviceItem.AppId = dr["AppID"].ToString();
                        deviceItem.Email = dr["Email"].ToString();
                        if (dr["LogDateSync"] != null && !string.IsNullOrEmpty(dr["LogDateSync"].ToString()))
                            deviceItem.LogSyncDate = Convert.ToDateTime(dr["LogDateSync"]);
                        deviceItem.Uuid = dr["Uuid"].ToString();
                        listDevice.Add(deviceItem);
                    }
                }
            }
            catch (Exception ex)
            {
                Global.log.Error(ex);
                throw;
            }
            return listDevice;
        }

        [WebMethod(Description = "Lay danh sach email de gui log")]
        public List<EmailAdmin> GetEmailAdmin(string AppID)
        {
            List<EmailAdmin> emailList = new List<EmailAdmin>();
            try
            {

                DataTable dt = new DataTable();
                using (MainDB db = new MainDB())
                {
                    dt = db.StoredProcedures.VNA_Select_EmailAdmin(AppID);
                    db.Close();
                    db.Dispose();
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        EmailAdmin emailAdmin = new EmailAdmin();
                        emailAdmin.Email = item["Email"].ToString();
                        emailAdmin.Name = item["Name"].ToString();
                        emailList.Add(emailAdmin);
                    }
                }
            }
            catch (Exception ex)
            {
                Global.log.Error(ex);
            }

            return emailList;
        }      
        
    }
}
